package org.mii.safeguard.v1.security.service;

import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.mii.safeguard.v1.entity.IdEntity;
import org.mii.safeguard.v1.security.entity.AuthorityIdentifier;
import org.springframework.util.Assert;

public class AuthorityUtils {

	/**
	 * 标记权限集合对于某待授权对象的授权状态
	 * 
	 * @param <T>
	 * @param allAuths
	 *            ：权限集合
	 * @param authoritedIds
	 *            ：待授权对象已有的权限id集合
	 * @param clazz
	 *            :权限类
	 * @param idName
	 *            :T的instance中ID的名字
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public static <T extends AuthorityIdentifier> void identifierAuths(
			List<T> allAuths, List<Long> authoritedIds, Class<T> clazz,
			String idName) throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		if (allAuths == null || authoritedIds == null)
			return;

		// 参数校验
		Assert.hasText(idName, "idName不能为空");
		Assert.notNull(clazz, "clazz不能为空");

		for (T obj : allAuths) {
			obj.setIsAuth("false");
		}

		for (T obj : allAuths) {
			for (Long id : authoritedIds) {

				Long objId = (Long) PropertyUtils.getProperty(obj, idName);
				// 标记该权限初始时是否已经授权给了指定的对象
				if (objId.equals(id)) {
					obj.setIsAuth("true");
					break;
				}
			}
		}
	}

	/**
	 * 根据传递来的id，更新原有的权限。如果原有权限包含该id，则在原来权限中删除，如果原来权限中没有该id，则添加
	 * 
	 * @param <T>
	 * @param authList权限List
	 * @param id带更新权限List的id
	 * @return int 1:添加了新权限;0:删除了该权限
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * 
	 * @author QUANXIWEI
	 */
	public static <T extends IdEntity> int updateAuthorites(Set<T> authList,
			Long id, Class<T> clazz) throws InstantiationException,
			IllegalAccessException {
		
		// 参数校验
		Assert.notNull(authList, "authList不能为空");
		Assert.notNull(clazz, "clazz不能为空");

		Iterator<T> iterator = authList.iterator();
		while (iterator.hasNext()) {
			T element = iterator.next();
			if (element.getId().equals(id)) {
				iterator.remove();
				return 0;// 删除一个权限
			}

		}

		T obj = clazz.newInstance();
		obj.setId(id);
		authList.add(obj);
		return 1;// 添加一个新权限
	}
}
